/*
 * Created on 2005-6-28
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.dcivision.dms.web;

import java.io.StringWriter;
import java.sql.Connection;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsCheckoutHistory;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentDetail;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DmsWinClientOperartionManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsDocumentDetailDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.dao.UserRecordDAObject;

/**
 * MaintWriteDocumentXmlAction
 *
 * 
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MaintWriteDocumentXmlAction extends AbstractMaintAction {
  
  public static final String REVISION = "$Revision: 1.12.2.2 $";
  
  private static final String ALLFOLDERLIST = "1";
  private static final String CURRENTFOLDERLSET = "2";
  private static final String CURRENTDOCUMENTLIST = "3";
  private static final String CURRENTEXTREFLIST = "4";
  //Get the folder's one level sub folders
  private static final String ONELEVFORDERLIST = "5";
  
  private static final String EMAIL_EXT = "EML";
  private static final String NOTES_EXT = ".dxl";  
  
  private String wrongType ="0";
  private String parameterWrong = "PARAMETER_WRONG";
  private String parameterMessage = "PASS PARAMETER IS WRONG";
  private String permissionWrong = "PERMISSION_WRONG";
  private String permissionMessage = "NO PERMISSION";
  private String changeWrong ="CHANGE_WRONG";
  private String changeMessage = "THE TREE IS ALREADY CHANGE";
  private String unknowWrong ="UNKNOW_WRONG";
  private String unknowMessage = "THE WRONG IS UNKNOW";
  
  private String haveSubFolder = "0";
  
  //String targetPath; 
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    haveSubFolder = "0";
    
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer,conn);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    UserRecordDAObject userRecordDAObject = new UserRecordDAObject(sessionContainer,conn); 
    VersionControlManager versionControlManager = new VersionControlManager(sessionContainer,conn); 
    
    MaintWriteDocumentXmlForm actionForm = (MaintWriteDocumentXmlForm)form;
    
    String ID = actionForm.getID();
    String rootID = actionForm.getRootID();
    String parentID = actionForm.getParentID();
    
    String targetPath1= "D:\\EIP\\Source\\web\\jsp\\odma\\odma_rootFolderList.xml";
    String targetPath2= "D:\\EIP\\Source\\web\\jsp\\odma\\odma_currentFolderList.xml";
    String targetPath3= "D:\\EIP\\Source\\web\\jsp\\odma\\odma_currentDocumentList.xml";
    try {
      if (this.CURRENTFOLDERLSET.equals(actionForm.getWriteType())){
        this.loadParaDoc(request,targetPath2,actionForm);
      }else if(this.CURRENTDOCUMENTLIST.equals(actionForm.getWriteType())){
        this.loadParaDoc(request,targetPath3,actionForm);
      }else if(this.CURRENTEXTREFLIST.equals(actionForm.getWriteType())){
        this.loadParaDoc(request,targetPath3,actionForm);
      }else{
        this.loadParaDoc(request,targetPath1,actionForm);
      }
    }catch (Exception e) {
      try{
        this.loadWrongMessage(wrongType, ID, request);  	      
      }catch (Exception ee){
        log.error(ee, ee);
      }
    }
    
    return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
  }
  
  /**
   * main method:get all DmsDocument tree according the specific user privillege,
   * then write to a xml called odma.xml 
   */
  public void loadParaDoc(HttpServletRequest request,String targetPath,ActionForm form) throws Exception{ 
    Document doc = newDocument();
    createDocumentDetail(doc,request,form); 
    writeToXml(doc,targetPath,request); 
  }
  
  /**
   *  new a empty Document
   */
  private Document newDocument() throws Exception{
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    return builder.newDocument(); 
  }
  
  /**
   *  write Document to a xml file.
   */
  private void writeToXml(Document doc,String targetPath,HttpServletRequest request) throws Exception{
    Source source = new DOMSource(doc); 
    /*File file = new File(targetPath);
     Result result = new StreamResult(file);
     Transformer xformer = TransformerFactory.newInstance().newTransformer();
     xformer.transform(source,result);*/
    StringWriter writer=new StringWriter();
    StreamResult result = new StreamResult(writer);	   
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(source, result);
    StringBuffer writerBuffer=new StringBuffer();
    writerBuffer.append(writer.toString());
    request.setAttribute("WriteXml",writer.toString());
  }
  
  /**
   *  add DmsDocument tree to a Document Object.
   */
  private void createDocumentDetail(Document doc,HttpServletRequest request,ActionForm form) throws Exception{
    MaintWriteDocumentXmlForm actionForm = (MaintWriteDocumentXmlForm)form;
    Element paraDoc = doc.createElement("para-doc");
    doc.appendChild(paraDoc);
    addParaUserXml(doc,paraDoc,request);
    if (this.CURRENTFOLDERLSET.equals(actionForm.getWriteType())){
      addCurrentFolderTree(doc,paraDoc,request,actionForm);
    }else if(this.CURRENTDOCUMENTLIST.equals(actionForm.getWriteType())){
      addCurrentDocumentTree(doc,paraDoc,request,actionForm);
    }else if(this.CURRENTEXTREFLIST.equals(actionForm.getWriteType())){
      addExtRefStr(doc,paraDoc,request,actionForm);
    }else if(this.ONELEVFORDERLIST.equals(actionForm.getWriteType())){
      addFolderTreeByParentIDRootID(doc,paraDoc,request,actionForm);      
    }else{
      addDocumentRootFolder(doc,paraDoc,request);
    }
  }
  
  private void addParaUserXml(Document rootDocument,Element parentElement,HttpServletRequest request) throws Exception{ 
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Element paraUser = rootDocument.createElement("paraUser");
    paraUser.setAttribute("loginName",sessionContainer.getUserRecord().getLoginName()); 
    java.util.Date currentDate = new java.util.Date(); 
    Format df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    paraUser.setAttribute("createTime",df.format(currentDate));
    parentElement.appendChild(paraUser);
  }
  
  private void addDocumentRootFolder(Document rootDocument,Element parentElement,HttpServletRequest request) throws Exception{ 
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer,conn);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    
    Element documentTree = rootDocument.createElement("documentTree"); 
    Element personal = rootDocument.createElement("personal"); 
    Element pub = rootDocument.createElement("public");
    parentElement.appendChild(documentTree);
    documentTree.appendChild(personal);
    documentTree.appendChild(pub);
    
    List rootsList = rootRetrievalManager.getAllAccessibleRootsList();
    //loop to get all root folder and add content.
    for (int i=0; i<rootsList.size(); i++) {
      haveSubFolder = "0";
      String permission = "";
      DmsRoot dmsRoot = (DmsRoot)rootsList.get(i); 
      DmsDocument doc =  documentRetrievalManager.getRootFolderByRootID(dmsRoot.getID());
      permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, doc.getID());
      
      List subFolder = documentRetrievalManager.getFolderByParentIDRootID(doc.getID(),dmsRoot.getID());
      if(!Utility.isEmpty(subFolder)){
        haveSubFolder = "1";
      }
      
      Element root = rootDocument.createElement("root"); 
      root.setAttribute("id",doc.getID().toString());
      root.setAttribute("name",dmsRoot.getRootName().toString()); 
      root.setAttribute("type",dmsRoot.getRootType().toString()); 
      root.setAttribute("rootID",dmsRoot.getID().toString());
      root.setAttribute("parentID",new String("0")); 
      root.setAttribute("permission",permission); 
      root.setAttribute("haveSubFolder",haveSubFolder); 
      if(dmsRoot.getRootType().trim().equals("P")){
        personal.appendChild(root); 
      }else if(dmsRoot.getRootType().trim().equals("U")){
        pub.appendChild(root); 
      }
    } 
  }
  
  
  private void addExtRefStr(Document rootDocument,Element parentElement,HttpServletRequest request,ActionForm form) throws Exception{ 
    MaintWriteDocumentXmlForm actionForm = (MaintWriteDocumentXmlForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    Element extRefs = rootDocument.createElement("ExtRefs"); 
    parentElement.appendChild(extRefs);
    List extRefList = dmsDocumentDAO.getAllExtRefList();
    if (!Utility.isEmpty(extRefList)){
      for(int i = 0 ; i< extRefList.size();i++){
        String extRefStr = (String)extRefList.get(i);
        if(!Utility.isEmpty(extRefStr)){
          Element extRef = rootDocument.createElement("ExtRef");
          extRef.setAttribute("value",extRefStr);
          extRefs.appendChild(extRef);          
        }

      }
    }
  }
    
  
  private void addCurrentFolderTree(Document rootDocument,Element parentElement,HttpServletRequest request,ActionForm form) throws Exception{ 
    MaintWriteDocumentXmlForm actionForm = (MaintWriteDocumentXmlForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer,conn);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer, conn);
    
    Element folderTree = rootDocument.createElement("folderTree"); 
    parentElement.appendChild(folderTree);
    
    String ID = actionForm.getID();
    String rootID = actionForm.getRootID();
    String parentID = actionForm.getParentID();
    haveSubFolder = "0";
    
    if(!Utility.isEmpty(ID)&&!Utility.isEmpty(rootID)&&!Utility.isEmpty(parentID)){
      DmsDocument dmsDocumentFolder = (DmsDocument)dmsDocumentDAO.getObjectByID(TextUtility.parseIntegerObj(ID));
      DmsRoot dmsRoot = (DmsRoot)dmsRootDAO.getObjectByID(TextUtility.parseIntegerObj(rootID));
      
      String permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(ID));
      List subFolder = documentRetrievalManager.getFolderByParentIDRootID(TextUtility.parseIntegerObj(ID),TextUtility.parseIntegerObj(rootID));
      if(!Utility.isEmpty(subFolder)){
        haveSubFolder = "1";
      }
      
      if((permission.indexOf("R") >= 0)){
        if((TextUtility.formatIntegerObj(dmsDocumentFolder.getRootID()).equals(rootID))&&(TextUtility.formatIntegerObj(dmsDocumentFolder.getParentID()).equals(parentID))){
          Element rootFolder = rootDocument.createElement("folder"); 
          rootFolder.setAttribute("id",dmsDocumentFolder.getID().toString()); 
          rootFolder.setAttribute("name",dmsDocumentFolder.getDocumentName());
          rootFolder.setAttribute("rootID",dmsDocumentFolder.getRootID().toString());
          rootFolder.setAttribute("parentID",dmsDocumentFolder.getParentID().toString());
          rootFolder.setAttribute("type",dmsRoot.getRootType().toString()); 
          rootFolder.setAttribute("permission",permission);
          rootFolder.setAttribute("haveSubFolder",haveSubFolder); 
          
          folderTree.appendChild(rootFolder);
          printFolder(dmsDocumentFolder,rootFolder,rootDocument,dmsRoot.getRootType().trim(),request);
        }//if tree is changed
        else{
          wrongType = "3";
          throw new Exception();
        }
      }//if no permission
      else{
        wrongType = "2";
        throw new Exception();
      }
    }//if parameter is empty
    else{
      wrongType = "1";
      throw new Exception();
    }
  }
  
  private void addCurrentDocumentTree(Document rootDocument,Element parentElement,HttpServletRequest request,ActionForm form) throws Exception{ 
    MaintWriteDocumentXmlForm actionForm = (MaintWriteDocumentXmlForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer,conn);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer, conn);
    
    Element documnetTree = rootDocument.createElement("documentTree"); 
    parentElement.appendChild(documnetTree);
    
    String ID = actionForm.getID();
    String rootID = actionForm.getRootID();
    String parentID = actionForm.getParentID();
    
    if(!Utility.isEmpty(ID)&&!Utility.isEmpty(rootID)&&!Utility.isEmpty(parentID)){
      DmsDocument dmsDocumentFolder = (DmsDocument)dmsDocumentDAO.getObjectByID(TextUtility.parseIntegerObj(ID));
      DmsRoot dmsRoot = (DmsRoot)dmsRootDAO.getObjectByID(TextUtility.parseIntegerObj(rootID));
      
      String permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(ID));
      
      if((permission.indexOf("R") >= 0)&&(TextUtility.formatIntegerObj(dmsDocumentFolder.getRootID()).equals(rootID))&&(TextUtility.formatIntegerObj(dmsDocumentFolder.getParentID()).equals(parentID))){
        if((TextUtility.formatIntegerObj(dmsDocumentFolder.getRootID()).equals(rootID))&&(TextUtility.formatIntegerObj(dmsDocumentFolder.getParentID()).equals(parentID))){
          Element rootFolder = rootDocument.createElement("folder"); 
          rootFolder.setAttribute("id",dmsDocumentFolder.getID().toString()); 
          rootFolder.setAttribute("name",dmsDocumentFolder.getDocumentName());
          rootFolder.setAttribute("rootID",dmsDocumentFolder.getRootID().toString());
          rootFolder.setAttribute("parentID",dmsDocumentFolder.getParentID().toString());
          rootFolder.setAttribute("type",dmsRoot.getRootType().toString()); 
          rootFolder.setAttribute("permission",permission);
          
          documnetTree.appendChild(rootFolder);
          printDocument(dmsDocumentFolder,rootFolder,rootDocument,dmsRoot.getRootType().trim(),request);
        }//if tree is changed
        else{
          wrongType = "3";
          throw new Exception();
        }
      }//if no permission
      else{
        wrongType = "2";
        throw new Exception();
      }
    }//if parameter is empty
    else{
      wrongType = "1";
      throw new Exception();
    }
  }
  
  private void addFolderTreeByParentIDRootID(Document rootDocument,Element parentElement,HttpServletRequest request,ActionForm form) throws Exception{ 
    MaintWriteDocumentXmlForm actionForm = (MaintWriteDocumentXmlForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer,conn);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DmsRootDAObject dmsRootDAO = new DmsRootDAObject(sessionContainer, conn);
    
    Element folderTree = rootDocument.createElement("folderTree"); 
    parentElement.appendChild(folderTree);
    
    String ID = actionForm.getID();
    String rootID = actionForm.getRootID();
    String parentID = actionForm.getParentID();
    haveSubFolder = "0";
    
    if(!Utility.isEmpty(ID)&&!Utility.isEmpty(rootID)&&!Utility.isEmpty(parentID)){
      DmsDocument dmsDocumentFolder = (DmsDocument)dmsDocumentDAO.getObjectByID(TextUtility.parseIntegerObj(ID));
      DmsRoot dmsRoot = (DmsRoot)dmsRootDAO.getObjectByID(TextUtility.parseIntegerObj(rootID));
      
      String permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, TextUtility.parseIntegerObj(ID));
      List subFolder = documentRetrievalManager.getFolderByParentIDRootID(TextUtility.parseIntegerObj(ID),TextUtility.parseIntegerObj(rootID));
      if(!Utility.isEmpty(subFolder)){
        haveSubFolder = "1";
      }
      
      if((permission.indexOf("R") >= 0)){
        if((TextUtility.formatIntegerObj(dmsDocumentFolder.getRootID()).equals(rootID))&&(TextUtility.formatIntegerObj(dmsDocumentFolder.getParentID()).equals(parentID))){
          Element rootFolder = rootDocument.createElement("folder");
          List list = documentRetrievalManager.getFolderByParentIDRootID(TextUtility.parseIntegerObj(ID),TextUtility.parseIntegerObj(rootID)); 
          if(list==null||list.size()==0) return;
          for (int j=0; j<list.size(); j++) { 
            haveSubFolder = "0";
            DmsDocument sonDmsDocument = (DmsDocument)list.get(j); 
            permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, sonDmsDocument.getID());
            
            if ("P".equals(sonDmsDocument.getRecordStatus())){
              continue;
            }
            
            subFolder = documentRetrievalManager.getFolderByParentIDRootID(sonDmsDocument.getID(),sonDmsDocument.getRootID());
            if(!Utility.isEmpty(subFolder)){
              haveSubFolder = "1";
            }
            
            if(permission.indexOf("R") >= 0){
              Element sonElement = null;
              sonElement =  rootDocument.createElement("folder");
              if (sonDmsDocument != null && sonElement != null){
                sonElement.setAttribute("id",sonDmsDocument.getID().toString()); 
                sonElement.setAttribute("name",sonDmsDocument.getDocumentName());
                sonElement.setAttribute("rootID",sonDmsDocument.getRootID().toString()); 
                sonElement.setAttribute("parentID",sonDmsDocument.getParentID().toString()); 
                sonElement.setAttribute("documentType",sonDmsDocument.getDocumentType()); 
                sonElement.setAttribute("permission",permission); 
                sonElement.setAttribute("haveSubFolder",haveSubFolder); 
                
                // personal folder 's document not need checkout message.
                if(dmsRoot.getRootType().equals("U")){
                  sonElement.setAttribute("itemStatus",sonDmsDocument.getItemStatus()); 
                  sonElement.setAttribute("checkedoutUser",getCheckedUserName(sonDmsDocument,request)); 
                }else{
                  sonElement.setAttribute("itemStatus","A"); 
                  sonElement.setAttribute("checkedoutUser",""); 
                }
                folderTree.appendChild(sonElement); 
                //printFolder(sonDmsDocument,sonElement,doc,rootType,request);
              }
            } 
          }          
          
          
        }//if tree is changed
        else{
          wrongType = "3";
          throw new Exception();
        }
      }//if no permission
      else{
        wrongType = "2";
        throw new Exception();
      }
    }//if parameter is empty
    else{
      wrongType = "1";
      throw new Exception();
    }
  }
  
  private void printFolder(DmsDocument dmsDocument,Element parentElement,Document doc,String rootType,HttpServletRequest request) throws Exception{ 
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    
    List l = documentRetrievalManager.getFolderByParentIDRootID(dmsDocument.getID(),dmsDocument.getRootID()); 
    if(l==null||l.size()==0) return;
    for (int j=0; j<l.size(); j++) { 
      haveSubFolder = "0";
      DmsDocument sonDmsDocument = (DmsDocument)l.get(j); 
      String permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, sonDmsDocument.getID());
      
      if ("P".equals(sonDmsDocument.getRecordStatus())){
        continue;
      }
      
      List subFolder = documentRetrievalManager.getFolderByParentIDRootID(sonDmsDocument.getID(),sonDmsDocument.getRootID());
      if(!Utility.isEmpty(subFolder)){
        haveSubFolder = "1";
      }
      
      if(permission.indexOf("R") >= 0){
        Element sonElement = null;
        if(DmsDocument.FOLDER_TYPE.equals(sonDmsDocument.getDocumentType())){
          sonElement =  doc.createElement("folder");
        }else if(DmsDocument.DOCUMENT_TYPE.equals(sonDmsDocument.getDocumentType())){
          sonElement =  doc.createElement("document");
        }else if(DmsDocument.COMPOUND_DOC_TYPE.equals(sonDmsDocument.getDocumentType())){
          sonElement = doc.createElement("compound-doc");
        }
        if (sonDmsDocument != null && sonElement != null){
          sonElement.setAttribute("id",sonDmsDocument.getID().toString()); 
          sonElement.setAttribute("name",sonDmsDocument.getDocumentName());
          sonElement.setAttribute("rootID",sonDmsDocument.getRootID().toString()); 
          sonElement.setAttribute("parentID",sonDmsDocument.getParentID().toString()); 
          sonElement.setAttribute("documentType",sonDmsDocument.getDocumentType()); 
          sonElement.setAttribute("permission",permission); 
          sonElement.setAttribute("haveSubFolder",haveSubFolder); 
          
          // personal folder 's document not need checkout message.
          if(rootType.equals("U")){
            sonElement.setAttribute("itemStatus",sonDmsDocument.getItemStatus()); 
            sonElement.setAttribute("checkedoutUser",getCheckedUserName(sonDmsDocument,request)); 
          }else{
            sonElement.setAttribute("itemStatus","A"); 
            sonElement.setAttribute("checkedoutUser",""); 
          }
          parentElement.appendChild(sonElement); 
          printFolder(sonDmsDocument,sonElement,doc,rootType,request);
        }
      } 
    }
  }
  
  private void printDocument(DmsDocument dmsDocument,Element parentElement,Document doc,String rootType,HttpServletRequest request) throws Exception{
    String docExt = request.getParameter("DocType") != null?request.getParameter("DocType"):"";
    String clientType = request.getParameter("clientType") != null?request.getParameter("clientType"):"";
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    PermissionManager permissionManager = sessionContainer.getPermissionManager();
    
    //try{
    //List l = documentRetrievalManager.getDocumentListByParentIDRootID(dmsDocument.getID(),dmsDocument.getRootID()); 
    List docList = documentRetrievalManager.getDocumentListByParentIDRootID(dmsDocument.getID(),dmsDocument.getRootID());
    List tmpList = new ArrayList();
    if(docList==null||docList.size()==0) return;
    
    //if (MaintWriteDocumentXmlAction.EMAIL_EXT.equals(docExt)){
    if (DmsWinClientOperartionManager.CLIENT_TYPE_MSOUTLOOK.equals(clientType)){    
      for (int k=0; k < docList.size(); k++){
        DmsDocument eDoc = (DmsDocument)docList.get(k);
        if(DmsDocument.EMAIL_DOC_TYPE.equals(eDoc.getDocumentType())){
          List subDocList = documentRetrievalManager.getDocumentListByParentIDRootID(eDoc.getID(),eDoc.getRootID());
          if (subDocList != null){
            for (int i=0;i<subDocList.size();i++){
              DmsDocument subDoc = (DmsDocument)subDocList.get(i);
              if (DmsDocument.ORIGINSLITY_EMAIL_TYPE.equals(subDoc.getDocumentType())){
                tmpList.add(subDoc);
              }
            }
          }
        } else if (DmsDocument.FOLDER_TYPE.equals(eDoc.getDocumentType())){
          tmpList.add(eDoc);
        }
      }
    }else if (DmsWinClientOperartionManager.CLIENT_TYPE_NOTES.equals(clientType)){
      for (int k=0; k < docList.size(); k++){
        DmsDocument eDoc = (DmsDocument)docList.get(k);
        if(DmsDocument.EMAIL_DOC_TYPE.equals(eDoc.getDocumentType())){
          List subDocList = documentRetrievalManager.getDocumentListByParentIDRootID(eDoc.getID(),eDoc.getRootID());
          if (subDocList != null){
            for (int i=0;i<subDocList.size();i++){
              DmsDocument subDoc = (DmsDocument)subDocList.get(i);
              if (DmsDocument.ORIGINSLITY_EMAIL_TYPE.equals(subDoc.getDocumentType()) &&
                  subDoc.getDocumentName().lastIndexOf(NOTES_EXT)!=-1){
                //set the originslity file's parent id is the mail's folder id
                subDoc.setParentID(eDoc.getParentID());
                tmpList.add(subDoc);
              }
            }
          }
        } else if (DmsDocument.FOLDER_TYPE.equals(eDoc.getDocumentType())){
          tmpList.add(eDoc);
        }
      }    
    }else {
      tmpList = docList;
    }
    
    for (int j=0; j<tmpList.size(); j++) { 
      DmsDocument sonDmsDocument = (DmsDocument)tmpList.get(j); 
      if(
          (DmsWinClientOperartionManager.CLIENT_TYPE_MSOUTLOOK.equals(clientType)&&          
          DmsDocument.ORIGINSLITY_EMAIL_TYPE.equals(sonDmsDocument.getDocumentType()))
          ||DmsWinClientOperartionManager.CLIENT_TYPE_MSWORD.endsWith(clientType)
          ||DmsWinClientOperartionManager.CLIENT_TYPE_NOTES.endsWith(clientType)
      ){
        
        String permission = permissionManager.getPermission(conn, GlobalConstant.OBJECT_TYPE_DOCUMENT, sonDmsDocument.getID());
        
        if ("P".equals(sonDmsDocument.getRecordStatus())){
          continue;
        }
        
        if(permission.indexOf("R") >= 0){
          Element sonElement = null;
          if(DmsDocument.FOLDER_TYPE.equals(sonDmsDocument.getDocumentType())){
            sonElement =  doc.createElement("folder");
          }else if(
              (DmsWinClientOperartionManager.CLIENT_TYPE_MSOUTLOOK.equals(clientType)&&          
                  DmsDocument.ORIGINSLITY_EMAIL_TYPE.equals(sonDmsDocument.getDocumentType()))
                  ||DmsWinClientOperartionManager.CLIENT_TYPE_MSWORD.endsWith(clientType)
                  ||DmsWinClientOperartionManager.CLIENT_TYPE_NOTES.endsWith(clientType)
          ){
            sonElement =  doc.createElement("document");
          }else if(DmsDocument.COMPOUND_DOC_TYPE.equals(sonDmsDocument.getDocumentType())){
            sonElement = doc.createElement("compound-doc");
          }
          DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionContainer,conn);
          DmsDocument newDocument = (DmsDocument)dmsDocumentDAO.getDocumentByID(sonDmsDocument.getID(),null);
          Integer documentID = newDocument.getParentID();
          DmsDocumentDetailDAObject dmsDocmentDetailDAO = new DmsDocumentDetailDAObject(sessionContainer, conn);
          List result = dmsDocmentDetailDAO.getListByDocumentID(documentID);
          String emailUDFMailFromID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILFROM_ID);
          String emailUDFMailToID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILTO_ID);
          String emailUDFCCToID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_CCTO_ID);
          String emailUDFSubjectID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_SUBJECT_ID);
          String emailUDFSendDateID = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_EMAILARCHIVE_PROFILE_EMAIL_DETAIL_MAILSENDDATE_ID);
          String from = "";
          String to = "";
          String cc = "";
          String subject = "";
          String sendDate = "";
          for(int i=0; i<result.size();i++){
        	  DmsDocumentDetail dmsDocumentDetail = (DmsDocumentDetail)result.get(i);
        	  if(dmsDocumentDetail.getUserDefinedFieldDetailID().toString().equals(emailUDFMailFromID)){
        		  from = dmsDocumentDetail.getFieldValue().toString();
        	  }else if(dmsDocumentDetail.getUserDefinedFieldDetailID().toString().equals(emailUDFMailToID)){
        		  to = dmsDocumentDetail.getFieldValue().toString();
        	  }else if(dmsDocumentDetail.getUserDefinedFieldDetailID().toString().equals(emailUDFCCToID)){
        		  cc = dmsDocumentDetail.getFieldValue().toString();
        	  }else if(dmsDocumentDetail.getUserDefinedFieldDetailID().toString().equals(emailUDFSubjectID)){
        		  subject = dmsDocumentDetail.getFieldValue().toString();
        	  }else if(dmsDocumentDetail.getUserDefinedFieldDetailID().toString().equals(emailUDFSendDateID)){
        		  sendDate = dmsDocumentDetail.getFieldValue().toString();
        	  }
          }
          if (sonDmsDocument != null && sonElement != null){
            sonElement.setAttribute("id",sonDmsDocument.getID().toString()); 
            sonElement.setAttribute("name",sonDmsDocument.getDocumentName());
            sonElement.setAttribute("rootID",sonDmsDocument.getRootID().toString()); 
            sonElement.setAttribute("parentID",sonDmsDocument.getParentID().toString()); 
            sonElement.setAttribute("documentType",sonDmsDocument.getDocumentType()); 
            sonElement.setAttribute("permission",permission); 
            sonElement.setAttribute("from",from);
            sonElement.setAttribute("to",to);
            sonElement.setAttribute("cc",cc);
            sonElement.setAttribute("subject",subject);
            sonElement.setAttribute("sendDate",sendDate);
            
            // personal folder 's document not need checkout message.
            if(rootType.equals("U")){
              sonElement.setAttribute("itemStatus",sonDmsDocument.getItemStatus()); 
              sonElement.setAttribute("checkedoutUser",getCheckedUserName(sonDmsDocument,request)); 
            }else{
              sonElement.setAttribute("itemStatus","A"); 
              sonElement.setAttribute("checkedoutUser",""); 
            }
            parentElement.appendChild(sonElement); 
            //printDocument(sonDmsDocument,sonElement,doc,rootType,request);
          }
        } 
      }
    }
  }
  
  private String getCheckedUserName(DmsDocument document,HttpServletRequest request)throws Exception{
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    
    //RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer,conn);
    //DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    UserRecordDAObject userRecordDAObject = new UserRecordDAObject(sessionContainer,conn); 
    VersionControlManager versionControlManager = new VersionControlManager(sessionContainer,conn); 
    
    String userName = ""; 
    DmsCheckoutHistory checkoutHistory = versionControlManager.getCurrentCheckoutDetail(document, DmsOperationConstant.DMS_TOP_VERSION);
    if (checkoutHistory != null) {
      UserRecord tmpUserRecord = (UserRecord)userRecordDAObject.getObjectByID(checkoutHistory.getCheckoutPersonID());
      userName = tmpUserRecord.getFullName();
    }
    return userName;
  }
  
  private void loadWrongMessage(String wrongType,String documentID, HttpServletRequest request) throws Exception{ 
    Document doc = newDocument();
    if("1".equals(wrongType)){
      printWrongMessage(doc,request,parameterWrong,parameterMessage,documentID); 
    }else if ("2".equals(wrongType)){
      printWrongMessage(doc,request,permissionWrong,permissionMessage,documentID); 
    }else if ("3".equals(wrongType)){
      printWrongMessage(doc,request,changeWrong,changeMessage,documentID); 
    }else{
      printWrongMessage(doc,request,unknowWrong,unknowMessage,documentID); 
    }	  
    writeToXml(doc,"",request); 
  }
  
  private void printWrongMessage(Document doc, HttpServletRequest request, String type, String message, String documentID) throws Exception{
    Element paraDoc = doc.createElement("para-wrong");
    doc.appendChild(paraDoc);
    addParaUserXml(doc,paraDoc,request);
    
    Element odmaWrong = doc.createElement("odmaWrong"); 
    odmaWrong.setAttribute("type",type); 
    odmaWrong.setAttribute("message",message);
    odmaWrong.setAttribute("documentID",documentID);
    paraDoc.appendChild(odmaWrong);
    
  }
  
  public String getFunctionCode() {
    return null;
  }
  
  public String getMajorDAOClassName() {
    return null;
  }
  
}
